#include "ScriptLoader.h"
//#include <elements.h>

namespace OpenNano
{
    ScriptLoader::ScriptLoader() :
                _rootElement(0),
                logger(log4cplus::Logger::getInstance("ScriptLoader"))
    {
        document = new TiXmlDocument();
        LOG4CPLUS_WARN(logger, "created");
    }

    ScriptLoader::~ScriptLoader()
    {
        delete document;
        ConfigMap::getInstance().clear();
        LOG4CPLUS_WARN(logger, "destroyed");

    }

    bool ScriptLoader::loadConfigFile(const std::string &filename)
    {
        LOG4CPLUS_WARN(logger, "loading config file");
        LOG4CPLUS_WARN(logger, filename);
        bool result = document->LoadFile(filename);
        if (result)
        {
            //TiXmlHandle docHandle( document );
            TiXmlElement * root(0);
            root = document->FirstChildElement(CONFIG_TAG)->ToElement();
            if (root)
            {
         //       ConfigElement * rootElement = ConfigElementFactory::getInstance().create(root->ValueStr())(root);

                _rootElement = (ConfigurationRootElement *) ConfigElementFactory::getInstance().create(root->ValueStr())(root);

                //ConfigMMap::getInstance().create(root->ValueStr())(root);
                result = _rootElement->process();
                if (!result)
                {
                    delete _rootElement;
                   LOG4CPLUS_ERROR(logger, "Configuration element not processed");
                }
                else
                {
                    ConfigMap::getInstance().insert(CM_Entry(CONFIG_TAG, _rootElement));
                }
            }
            else
            {
                LOG4CPLUS_ERROR(logger, "config file invalid");
                result=false;
                //NOTE_TO_SELF
                //this is not a valid configuration file!
            }
        }
        else
        {
            LOG4CPLUS_ERROR(logger, "config file does not exist");
        }
        return result;

    }

    const ConfigurationMap & ScriptLoader::getConfigurations() const
    {

        return ConfigMap::getInstance();;
    }
}
